﻿Imports TNCDAL
Imports DevComponents.DotNetBar.Controls
Imports HTLibrary

Public Class ucTruck_Accessory
    Dim db As New TanNamChinhDataContext
    Dim m_loai_dtg As Integer = 0
    Dim m_Type As Integer = 1 ' 1 - Truck, 2 - Cont

    Public Sub New(ByVal Type As Integer)

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        m_Type = Type

        If Type = 1 Then
            lblTruck.Text = "Truck No"
        ElseIf Type = 2 Then
            lblTruck.Text = "Cont No"
        End If
        DataGridViewHelper.DataGridView_InitEvent(dtgAccessory)
    End Sub

    Private Sub frmTruck_Accessory_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            KhoiTaocbbTruck()
            KhoiTaoThuocTinhlvAccessory()
            KhoiTaolvAccessory()
            Bar1.AutoHide = True
            Try
                FormatdtgAccessory()
            Catch ex As Exception

            End Try
            KhoiTaodtgFixProgress(0)
            FormatdtgFixProgress()
            KhoiTaoGiaoDienAccessory(True)
            KhoiTaoGiaoDienRepair(True)
        Catch ex As Exception

        End Try
    End Sub

    Public Sub KhoiTaoThuocTinhlvAccessory()
        lvAccessory.View = View.Details
        lvAccessory.BackColor = Color.White
        lvAccessory.FullRowSelect = True
        lvAccessory.Columns.Add("Phụ tùng", 160)
    End Sub

    Public Sub KhoiTaolvAccessory()
        Dim accessory = From p In db.tblAccessories
                        Where p.Type = m_Type And p.IsActive = True
                        Select p
                        Order By p.AccessoryName
        lvAccessory.Items.Clear()

        For Each p As tblAccessory In accessory
            Dim item As New ListViewItem
            item.Text = p.AccessoryName
            item.Name = p.ID_Accessory
            lvAccessory.Items.Add(item)
        Next
    End Sub

    Public Sub KhoiTaocbbTruck()
        Dim truck = From p In db.tblTrucks
                    Where p.Type = m_Type And p.IsActive = True
                    Select New With {p.ID_Truck, p.TruckNumber}

        cbbTruck.DataSource = truck
        cbbTruck.DisplayMember = "TruckNumber"
        cbbTruck.ValueMember = "ID_Truck"
        cbbTruck.SelectedIndex = -1
        'FormatdtgTruck()
    End Sub

    Public Sub KhoiTaodtgAccessory(ByVal id_truck As Integer)
        Dim accessory = db.GetAccessoryByTruck(id_truck)
        'Dim accessory = From p In db.tblTruckAccessories
        '                Where p.ID_Truck = id_truck And p.tblAccessory.IsActive = True
        '                Select p.tblAccessory.ID_Accessory, p.tblAccessory.AccessoryName



        dtgAccessory.DataSource = accessory
    End Sub

    Function GetColumnDateTime(ByVal PropertyName As String, ByVal HeaderText As String, ByVal ColumnName As String) As DataGridViewDateTimeInputColumn
        Dim DateC As New DataGridViewDateTimeInputColumn
        DateC.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None
        
        DateC.Name = ColumnName
        DateC.ButtonClear.Visible = True
        DateC.ButtonDropDown.Visible = True
        DateC.ButtonCustom.Visible = False
        DateC.ButtonCustom2.Visible = False
        DateC.ButtonFreeText.Visible = False
        DateC.ButtonClear.DisplayPosition = 2
        DateC.ButtonCustom.DisplayPosition = 1

        DateC.DataPropertyName = PropertyName
        DateC.Format = DevComponents.Editors.eDateTimePickerFormat.[Custom]
        DateC.CustomFormat = "dd/MM/yyyy"
        DateC.HeaderText = HeaderText
        DateC.InputHorizontalAlignment = DevComponents.Editors.eHorizontalAlignment.Left
        DateC.MonthCalendar.AnnuallyMarkedDates = New Date(-1) {}
        DateC.MonthCalendar.BackgroundStyle.BackColor = System.Drawing.SystemColors.Window
        DateC.MonthCalendar.BackgroundStyle.Class = ""
        DateC.MonthCalendar.BackgroundStyle.CornerType = DevComponents.DotNetBar.eCornerType.Square
        DateC.MonthCalendar.CommandsBackgroundStyle.Class = ""
        DateC.MonthCalendar.CommandsBackgroundStyle.CornerType = DevComponents.DotNetBar.eCornerType.Square
        DateC.MonthCalendar.DisplayMonth = New Date(2010, 5, 1, 0, 0, 0, 0)
        DateC.MonthCalendar.MarkedDates = New Date(-1) {}
        DateC.MonthCalendar.MonthlyMarkedDates = New Date(-1) {}
        DateC.MonthCalendar.NavigationBackgroundStyle.Class = ""
        DateC.MonthCalendar.NavigationBackgroundStyle.CornerType = DevComponents.DotNetBar.eCornerType.Square
        DateC.MonthCalendar.WeeklyMarkedDays = New System.DayOfWeek(-1) {}
        DateC.Name = "BuyingDate"
        DateC.Resizable = System.Windows.Forms.DataGridViewTriState.[True]
        DateC.ShowUpDown = False
        DateC.Width = 100

        Return DateC
    End Function

    Public Sub FormatdtgAccessory()
        Dim BuyingDate As DataGridViewDateTimeInputColumn
        BuyingDate = GetColumnDateTime("BuyingDate", "Ngày mua", "NgayMua")
        dtgAccessory.Columns.Add(BuyingDate)

        Dim WarrantyDate As DataGridViewDateTimeInputColumn
        WarrantyDate = GetColumnDateTime("WarrantyDate", "Bảo hành", "BaoHanh")
        dtgAccessory.Columns.Add(WarrantyDate)

        'dtgAccessory.RowHeadersWidth = 20
        dtgAccessory.RowHeadersDefaultCellStyle.ForeColor = Color.Blue
        dtgAccessory.EditMode = DataGridViewEditMode.EditOnEnter
        'dtgAccessory.RowTemplate.Height = 25
        dtgAccessory.AllowUserToAddRows = False
        dtgAccessory.MultiSelect = False
        dtgAccessory.SelectionMode = DataGridViewSelectionMode.FullRowSelect
        dtgAccessory.BackgroundColor = Color.White
        dtgAccessory.Columns("ID_TruckAccessory").Visible = False
        dtgAccessory.Columns("ID_Truck").Visible = False
        dtgAccessory.Columns("ID_Accessory").Visible = False
        dtgAccessory.Columns("Status").Visible = False
        dtgAccessory.Columns("BuyingDate").Visible = False
        dtgAccessory.Columns("WarrantyDate").Visible = False

        With dtgAccessory.Columns("AccessoryName")
            .HeaderText = "Phụ tùng"
            .ReadOnly = True
            .Width = 140
        End With

        With dtgAccessory.Columns("SerialNumber")
            .HeaderText = "Số Serial"
            .Width = 140
        End With

        With dtgAccessory.Columns("Price")
            .HeaderText = "Giá"
            .Width = 90
            .DefaultCellStyle.Format = "#,###"
            .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        End With
    End Sub

    Public Sub KhoiTaodtgFixProgress(ByVal ID_TruckAccessory As Integer)
        Dim fixProgress = db.GetFixProgressByTruckAccessory(ID_TruckAccessory)

        dtgFixProgress.DataSource = fixProgress
        'FormatdtgFixProgress()
    End Sub

    Public Sub FormatdtgFixProgress()
        Dim BuyingDate As DataGridViewDateTimeInputColumn
        BuyingDate = GetColumnDateTime("RepairDate", "Ngày sửa", "NgaySua")
        dtgFixProgress.Columns.Add(BuyingDate)

        Dim WarrantyDate As DataGridViewDateTimeInputColumn
        WarrantyDate = GetColumnDateTime("RepairWarrantyDate", "Bảo hành", "BaoHanh")
        dtgFixProgress.Columns.Add(WarrantyDate)

        dtgFixProgress.RowHeadersWidth = 20
        dtgFixProgress.RowHeadersDefaultCellStyle.ForeColor = Color.Blue
        dtgFixProgress.EditMode = DataGridViewEditMode.EditOnEnter
        dtgFixProgress.RowTemplate.Height = 25
        dtgFixProgress.MultiSelect = False
        dtgFixProgress.SelectionMode = DataGridViewSelectionMode.FullRowSelect
        dtgFixProgress.BackgroundColor = Color.White
        dtgFixProgress.AllowUserToDeleteRows = False

        For i As Integer = 0 To 6
            dtgFixProgress.Columns(i).Visible = False
        Next
        dtgFixProgress.Columns("Status").Visible = False

        With dtgFixProgress.Columns("RepairOrder")
            .HeaderText = "STT"
            .ReadOnly = True
            .Width = 40
            .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        End With

        With dtgFixProgress.Columns("DescriptionRepair")
            .HeaderText = "Lý do sửa chữa"
            .Width = 250
        End With

        With dtgFixProgress.Columns("RepairPrice")
            .HeaderText = "Giá"
            .Width = 80
            .DefaultCellStyle.Format = "#,###"
            .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        End With
        dtgFixProgress.Columns("RepairDate").Visible = False
        dtgFixProgress.Columns("RepairWarrantyDate").Visible = False

        'With dtgFixProgress.Columns("RepairDate")
        '    .HeaderText = "Ngày sửa"
        '    .Width = 80
        '    .DefaultCellStyle.Format = "dd/MM/yyyy"
        '    .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        'End With

        'With dtgFixProgress.Columns("RepairWarrantyDate")
        '    .HeaderText = "Bảo hành"
        '    .Width = 80
        '    .DefaultCellStyle.Format = "dd/MM/yyyy"
        '    .DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        'End With
    End Sub

#Region "Formatting dtgAccessory"
    'Private Sub dtgAccessory_UserAddedRow(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowEventArgs) Handles dtgAccessory.UserAddedRow
    '    dtgAccessory.Rows(e.Row.Index - 1).Cells("Status").Value = 1
    '    'dtgAccessory.Rows(e.Row.Index - 1).Cells("ID_Truck").Value = dtgTruck.CurrentRow.Cells("ID_Truck").Value
    'End Sub

    Private Sub dtgAccessory_UserDeletingRow(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowCancelEventArgs) Handles dtgAccessory.UserDeletingRow
        If Not btnEdit.Enabled Then
            If e.Row.Cells("Status").Value = 0 Or e.Row.Cells("Status").Value = 2 Then
                e.Row.Cells("Status").Value = 3
                e.Cancel = True
            End If
        Else
            e.Cancel = True
        End If
    End Sub

    Private Sub dtgAccessory_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dtgAccessory.CellValueChanged
        Try
            If dtgAccessory.CurrentRow.Cells("Status").Value = 0 And e.RowIndex <> -1 Then
                dtgAccessory.CurrentRow.Cells("Status").Value = 2
            End If
        Catch ex As Exception

        End Try

    End Sub

    Private Sub dtgAccessory_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles dtgAccessory.CellFormatting
        Dim f As Font = dtgAccessory.DefaultCellStyle.Font
        If dtgAccessory.Rows(e.RowIndex).Cells("Status").Value = 1 Then
            ' Add row
            dtgAccessory.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.Black
            dtgAccessory.Rows(e.RowIndex).DefaultCellStyle.Font = New Font(f, FontStyle.Bold)
            Enable_datagird(1)
        ElseIf dtgAccessory.Rows(e.RowIndex).Cells("Status").Value = 2 Then
            'Update(row)
            dtgAccessory.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.Blue
            dtgAccessory.Rows(e.RowIndex).DefaultCellStyle.Font = New Font(f, FontStyle.Italic)
            Enable_datagird(1)
        ElseIf dtgAccessory.Rows(e.RowIndex).Cells("Status").Value = 3 Then
            ' Del row
            dtgAccessory.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.Red
            dtgAccessory.Rows(e.RowIndex).DefaultCellStyle.Font = New Font(f, FontStyle.Strikeout)
            Enable_datagird(1)
        End If
    End Sub


#End Region

    Private Sub dtgAccessory_CurrentCellChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dtgAccessory.CurrentCellChanged
        Try
            Dim ID_TruckAccessory As Integer
            ID_TruckAccessory = dtgAccessory.CurrentRow.Cells("ID_TruckAccessory").Value
            KhoiTaodtgFixProgress(ID_TruckAccessory)
        Catch ex As Exception
            KhoiTaodtgFixProgress(0)
        End Try

    End Sub

    Private Sub dtgFixProgress_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles dtgFixProgress.CellFormatting
        Dim f As Font = dtgFixProgress.DefaultCellStyle.Font
        If dtgFixProgress.Rows(e.RowIndex).Cells("Status").Value = 1 Then
            ' Add row
            dtgFixProgress.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.Black
            dtgFixProgress.Rows(e.RowIndex).DefaultCellStyle.Font = New Font(f, FontStyle.Bold)
            Enable_datagird(2)
        ElseIf dtgFixProgress.Rows(e.RowIndex).Cells("Status").Value = 2 Then
            'Update(row)
            dtgFixProgress.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.Blue
            dtgFixProgress.Rows(e.RowIndex).DefaultCellStyle.Font = New Font(f, FontStyle.Italic)
            Enable_datagird(2)

        ElseIf dtgFixProgress.Rows(e.RowIndex).Cells("Status").Value = 3 Then
            ' Del row
            dtgFixProgress.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.Red
            dtgFixProgress.Rows(e.RowIndex).DefaultCellStyle.Font = New Font(f, FontStyle.Strikeout)
            Enable_datagird(2)
        End If
    End Sub

    Private Sub dtgFixProgress_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dtgFixProgress.CellValueChanged
        Try
            If dtgFixProgress.CurrentRow.Cells("Status").Value = 0 And e.RowIndex <> -1 Then
                dtgFixProgress.CurrentRow.Cells("Status").Value = 2
            End If
        Catch ex As Exception

        End Try
    End Sub

    Private Sub dtgFixProgress_UserAddedRow(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowEventArgs) Handles dtgFixProgress.UserAddedRow
        dtgFixProgress.Rows(e.Row.Index - 1).Cells("Status").Value = 1
        '
        Dim ID_TruckAccessory As Integer = dtgAccessory.CurrentRow.Cells("ID_TruckAccessory").Value
        dtgFixProgress.Rows(e.Row.Index - 1).Cells("ID_TruckAccessory").Value = ID_TruckAccessory
        'RepairOrder tăng dần
        dtgFixProgress.Rows(e.Row.Index - 1).Cells("RepairOrder").Value = e.Row.Index
    End Sub

    Private Sub dtgFixProgress_UserDeletingRow(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowCancelEventArgs) Handles dtgFixProgress.UserDeletingRow
        If Not btnEditRepair.Enabled Then
            If e.Row.Cells("Status").Value = 0 Or e.Row.Cells("Status").Value = 2 Then
                e.Row.Cells("Status").Value = 3
                e.Cancel = True
            Else
                e.Cancel = True
            End If
        Else
            e.Cancel = True
        End If
    End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

        'If m_loai_dtg = 1 Then
        '    'dtgAccessory is used
        '    Dim ID_Truck As Integer
        '    ID_Truck = cbbTruck.SelectedValue

        '    For i As Integer = 0 To dtgAccessory.Rows.Count - 1
        '        Dim ID_TruckAccessory As Integer
        '        ID_TruckAccessory = dtgAccessory.Rows(i).Cells("ID_TruckAccessory").Value
        '        If dtgAccessory.Rows(i).Cells("Status").Value = 1 Then
        '            ' Add row
        '            Dim truck_accessory As New tblTruckAccessory
        '            truck_accessory.ID_Truck = ID_Truck
        '            truck_accessory.ID_Accessory = dtgAccessory.Rows(i).Cells("ID_Accessory").Value
        '            truck_accessory.SerialNumber = dtgAccessory.Rows(i).Cells("SerialNumber").Value
        '            truck_accessory.BuyingDate = dtgAccessory.Rows(i).Cells("BuyingDate").Value
        '            truck_accessory.WarrantyDate = dtgAccessory.Rows(i).Cells("WarrantyDate").Value
        '            truck_accessory.Price = dtgAccessory.Rows(i).Cells("Price").Value
        '            db.tblTruckAccessories.InsertOnSubmit(truck_accessory)
        '            db.SubmitChanges()
        '        ElseIf dtgAccessory.Rows(i).Cells("Status").Value = 2 Then
        '            ' Update row
        '            Dim truck_accessory = (From p In db.tblTruckAccessories
        '                       Where p.ID_TruckAccessory = ID_TruckAccessory
        '                       Select p).Single
        '            truck_accessory.ID_Truck = ID_Truck
        '            truck_accessory.ID_Accessory = dtgAccessory.Rows(i).Cells("ID_Accessory").Value
        '            truck_accessory.SerialNumber = dtgAccessory.Rows(i).Cells("SerialNumber").Value
        '            truck_accessory.BuyingDate = dtgAccessory.Rows(i).Cells("BuyingDate").Value
        '            truck_accessory.WarrantyDate = dtgAccessory.Rows(i).Cells("WarrantyDate").Value
        '            truck_accessory.Price = dtgAccessory.Rows(i).Cells("Price").Value
        '            db.SubmitChanges()
        '        ElseIf dtgAccessory.Rows(i).Cells("Status").Value = 3 Then
        '            ' Del row
        '            Dim truck_accessory = From p In db.tblTruckAccessories
        '                       Where p.ID_TruckAccessory = ID_TruckAccessory
        '                       Select p
        '            db.tblTruckAccessories.DeleteAllOnSubmit(truck_accessory)
        '            db.SubmitChanges()
        '        End If
        '    Next
        '    MsgBox("Đã lưu danh sách phụ tùng vào dữ liệu")

        '    KhoiTaodtgAccessory(ID_Truck)
        'ElseIf m_loai_dtg = 2 Then
        '    'dtgFixProgress is used
        '    'Cập nhật quá trình sửa chữa.
        '    'Cập nhật lại Order (đánh lại số thứ tự)
        '    Dim ID_TruckAccessory As Integer = dtgAccessory.CurrentRow.Cells("ID_TruckAccessory").Value

        '    Dim stt As Integer = 1
        '    For i As Integer = 0 To dtgFixProgress.Rows.Count - 2
        '        Dim order As Integer
        '        order = dtgFixProgress.Rows(i).Cells("RepairOrder").Value

        '        If dtgFixProgress.Rows(i).Cells("Status").Value = 1 Then
        '            ' Add row
        '            Dim fix As New tblFixProgress
        '            fix.ID_TruckAccessory = ID_TruckAccessory
        '            fix.RepairOrder = stt
        '            fix.DescriptionRepair = dtgFixProgress.Rows(i).Cells("DescriptionRepair").Value
        '            fix.RepairDate = dtgFixProgress.Rows(i).Cells("RepairDate").Value
        '            fix.RepairWarrantyDate = dtgFixProgress.Rows(i).Cells("RepairWarrantyDate").Value
        '            fix.RepairPrice = dtgFixProgress.Rows(i).Cells("RepairPrice").Value
        '            db.tblFixProgresses.InsertOnSubmit(fix)
        '            db.SubmitChanges()
        '        ElseIf dtgFixProgress.Rows(i).Cells("Status").Value = 2 Or dtgFixProgress.Rows(i).Cells("Status").Value = 0 Then
        '            ' Update row 

        '            'Dim fix = (From p In db.tblFixProgresses
        '            '           Where p.ID_TruckAccessory = ID_TruckAccessory And p.RepairOrder = order
        '            '           Select p).Single
        '            'fix.ID_TruckAccessory = ID_TruckAccessory
        '            'fix.RepairOrder = stt
        '            'fix.DescriptionRepair = dtgFixProgress.Rows(i).Cells("DescriptionRepair").Value
        '            'fix.RepairDate = dtgFixProgress.Rows(i).Cells("RepairDate").Value
        '            'fix.RepairWarrantyDate = dtgFixProgress.Rows(i).Cells("RepairWarrantyDate").Value
        '            'fix.RepairPrice = dtgFixProgress.Rows(i).Cells("RepairPrice").Value
        '            'db.SubmitChanges()

        '            'Update row new when change a primary key
        '            'Delete and insert
        '            '1.Delete
        '            Dim fix = From p In db.tblFixProgresses
        '                       Where p.ID_TruckAccessory = ID_TruckAccessory And p.RepairOrder = order
        '                       Select p
        '            db.tblFixProgresses.DeleteAllOnSubmit(fix)
        '            db.SubmitChanges()

        '            '2. Insert
        '            Dim fixnew As New tblFixProgress
        '            fixnew.ID_TruckAccessory = ID_TruckAccessory
        '            fixnew.RepairOrder = stt
        '            fixnew.DescriptionRepair = dtgFixProgress.Rows(i).Cells("DescriptionRepair").Value
        '            fixnew.RepairDate = dtgFixProgress.Rows(i).Cells("RepairDate").Value
        '            fixnew.RepairWarrantyDate = dtgFixProgress.Rows(i).Cells("RepairWarrantyDate").Value
        '            fixnew.RepairPrice = dtgFixProgress.Rows(i).Cells("RepairPrice").Value
        '            db.tblFixProgresses.InsertOnSubmit(fixnew)
        '            db.SubmitChanges()

        '        ElseIf dtgFixProgress.Rows(i).Cells("Status").Value = 3 Then
        '            ' Del row
        '            Dim fix = From p In db.tblFixProgresses
        '                       Where p.ID_TruckAccessory = ID_TruckAccessory And p.RepairOrder = order
        '                       Select p
        '            db.tblFixProgresses.DeleteAllOnSubmit(fix)
        '            db.SubmitChanges()
        '            stt -= 1
        '        End If
        '        stt += 1
        '    Next
        '    MsgBox("Đã lưu quá trình sửa chữa vào dữ liệu")

        '    KhoiTaodtgFixProgress(ID_TruckAccessory)
        'End If

        'dtgAccessory.Enabled = True
        'cbbTruck.Enabled = True
        'dtgFixProgress.Enabled = True
    End Sub
    
    Private Sub lvAccessory_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvAccessory.DoubleClick
        If cbbTruck.SelectedIndex = -1 Then
            Exit Sub
        End If

        ' kiem tra dtgAccessory đang cập nhật hay không/
        For i As Integer = 0 To dtgAccessory.RowCount - 1
            If dtgAccessory.Item("Status", i).Value > 0 Then
                MsgBox("Dữ liệu đang chỉnh sửa. Bạn nên cập nhật trước khi thêm phụ tùng mới")
                Exit Sub
            End If
        Next

        Dim ID_Truck As Integer = 0
        ID_Truck = cbbTruck.SelectedValue

        Dim AccessoryName As String
        Dim ID_Accessory As Integer

        AccessoryName = lvAccessory.SelectedItems(0).Text
        ID_Accessory = lvAccessory.SelectedItems(0).Name

        Dim truck_accessory As New tblTruckAccessory
        truck_accessory.ID_Truck = ID_Truck
        truck_accessory.ID_Accessory = ID_Accessory
        truck_accessory.BuyingDate = Now.Date
        truck_accessory.WarrantyDate = Now.Date
        truck_accessory.Price = 0

        db.tblTruckAccessories.InsertOnSubmit(truck_accessory)
        db.SubmitChanges()
        KhoiTaodtgAccessory(ID_Truck)
    End Sub

    Public Sub Enable_datagird(ByVal loai_dtg As Integer)
        If loai_dtg = 1 Then
            'Sửa dtgAccessory
            cbbTruck.Enabled = False
            dtgFixProgress.Enabled = False
            m_loai_dtg = 1
        ElseIf loai_dtg = 2 Then
            'Sửa dtgFixProgress
            cbbTruck.Enabled = False
            dtgAccessory.Enabled = False
            m_loai_dtg = 2
        End If
    End Sub

    Private Sub btnCopy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCopy.Click
        Dim ID_Truck As Integer = 0
        ID_Truck = cbbTruck.SelectedValue
        Dim SoXe As String = cbbTruck.SelectedText
        Dim SoXeCopy As String = ""

        If m_Type = 1 Then
            SoXeCopy = InputBox("Nhập số xe để copy danh mục phụ tùng vào xe: " + SoXe)
        ElseIf m_Type = 2 Then
            SoXeCopy = InputBox("Nhập số cont để copy danh mục phụ tùng vào cont: " + SoXe)
        End If

        'kiem tra xe
        Dim truck = (From p In db.tblTrucks
                     Where p.TruckNumber = SoXeCopy And p.Type = m_Type
                     Select p).SingleOrDefault

        If truck Is Nothing Then
            If m_Type = 1 Then
                MsgBox("Số xe copy không tồn tại.")
            ElseIf m_Type = 2 Then
                MsgBox("Số cont copy không tồn tại.")
            End If
            Exit Sub
        End If

        Dim accessory = From p In db.tblTruckAccessories
                        Where p.ID_Truck = truck.ID_Truck
                        Select p

        For Each acs As tblTruckAccessory In accessory
            Dim truck_accessory As New tblTruckAccessory
            truck_accessory.ID_Truck = ID_Truck
            truck_accessory.ID_Accessory = acs.ID_Accessory
            truck_accessory.SerialNumber = acs.SerialNumber
            truck_accessory.BuyingDate = acs.BuyingDate
            truck_accessory.WarrantyDate = acs.WarrantyDate
            truck_accessory.Price = acs.Price
            db.tblTruckAccessories.InsertOnSubmit(truck_accessory)
            db.SubmitChanges()
        Next

        KhoiTaodtgAccessory(ID_Truck)
    End Sub

    Private Sub btnCancel1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        dtgAccessory.Enabled = True
        cbbTruck.Enabled = True
        dtgFixProgress.Enabled = True

        If m_loai_dtg = 1 Then
            Dim ID_Truck As Integer = 0
            'ID_Truck = dtgTruck.CurrentRow.Cells("ID_Truck").Value
            KhoiTaodtgAccessory(ID_Truck)
        ElseIf m_loai_dtg = 2 Then
            Dim ID_TruckAccessory As Integer = 0
            ID_TruckAccessory = dtgAccessory.CurrentRow.Cells("ID_TruckAccessory").Value
            KhoiTaodtgFixProgress(ID_TruckAccessory)
        End If
    End Sub

    Private Sub cbbTruck_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cbbTruck.SelectedIndexChanged
        Try
            Dim ID_Truck As Integer = 0
            Try
                ID_Truck = cbbTruck.SelectedValue
            Catch ex As Exception

            End Try
            KhoiTaodtgAccessory(ID_Truck)
        Catch ex As Exception

        End Try
    End Sub

#Region "btn Edit, Del, Update, Cancel Truck_Accessory"
    Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click
        KhoiTaoGiaoDienAccessory(False)
    End Sub

    Private Sub btnDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDel.Click
        Dim AccessoryName As String = ""
        AccessoryName = dtgAccessory.CurrentRow.Cells("AccessoryName").Value

        If MsgBox("Bạn muốn xóa phụ tùng " + AccessoryName + " và quá trình sửa chữa.", MsgBoxStyle.YesNo, "Chú ý") = MsgBoxResult.Yes Then
            Dim ID_TruckAccessory As Integer
            ID_TruckAccessory = dtgAccessory.CurrentRow.Cells("ID_TruckAccessory").Value

            'Del qua trinh sua chua
            Dim fix_progress = From p In db.tblFixProgresses
                               Where p.ID_TruckAccessory = ID_TruckAccessory
                               Select p

            db.tblFixProgresses.DeleteAllOnSubmit(fix_progress)
            db.SubmitChanges()

            'Del phu tung khoi xe
            Dim truck_accessory = From p In db.tblTruckAccessories
                               Where p.ID_TruckAccessory = ID_TruckAccessory
                               Select p
            db.tblTruckAccessories.DeleteAllOnSubmit(truck_accessory)
            db.SubmitChanges()

            Dim ID_Truck As Integer
            ID_Truck = cbbTruck.SelectedValue
            KhoiTaodtgAccessory(ID_Truck)
        End If
    End Sub

    Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
        'dtgAccessory is used
        Dim ID_Truck As Integer
        ID_Truck = cbbTruck.SelectedValue

        For i As Integer = 0 To dtgAccessory.Rows.Count - 1
            Dim ID_TruckAccessory As Integer
            ID_TruckAccessory = dtgAccessory.Rows(i).Cells("ID_TruckAccessory").Value
            If dtgAccessory.Rows(i).Cells("Status").Value = 1 Then
                ' Add row
                Dim truck_accessory As New tblTruckAccessory
                truck_accessory.ID_Truck = ID_Truck
                truck_accessory.ID_Accessory = dtgAccessory.Rows(i).Cells("ID_Accessory").Value
                truck_accessory.SerialNumber = dtgAccessory.Rows(i).Cells("SerialNumber").Value
                truck_accessory.BuyingDate = dtgAccessory.Rows(i).Cells("BuyingDate").Value
                truck_accessory.WarrantyDate = dtgAccessory.Rows(i).Cells("WarrantyDate").Value
                truck_accessory.Price = dtgAccessory.Rows(i).Cells("Price").Value
                db.tblTruckAccessories.InsertOnSubmit(truck_accessory)
                db.SubmitChanges()
            ElseIf dtgAccessory.Rows(i).Cells("Status").Value = 2 Then
                ' Update row
                Dim truck_accessory = (From p In db.tblTruckAccessories
                           Where p.ID_TruckAccessory = ID_TruckAccessory
                           Select p).Single
                truck_accessory.ID_Truck = ID_Truck
                truck_accessory.ID_Accessory = dtgAccessory.Rows(i).Cells("ID_Accessory").Value
                truck_accessory.SerialNumber = dtgAccessory.Rows(i).Cells("SerialNumber").Value
                truck_accessory.BuyingDate = dtgAccessory.Rows(i).Cells("BuyingDate").Value
                truck_accessory.WarrantyDate = dtgAccessory.Rows(i).Cells("WarrantyDate").Value
                truck_accessory.Price = dtgAccessory.Rows(i).Cells("Price").Value
                db.SubmitChanges()
            ElseIf dtgAccessory.Rows(i).Cells("Status").Value = 3 Then
                ' Del row
                Dim truck_accessory = From p In db.tblTruckAccessories
                           Where p.ID_TruckAccessory = ID_TruckAccessory
                           Select p
                db.tblTruckAccessories.DeleteAllOnSubmit(truck_accessory)
                db.SubmitChanges()
            End If
        Next

        KhoiTaodtgAccessory(ID_Truck)
        KhoiTaoGiaoDienAccessory(True)
        dtgAccessory.Enabled = True
        cbbTruck.Enabled = True
        dtgFixProgress.Enabled = True
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        KhoiTaoGiaoDienAccessory(True)
    End Sub

    Public Sub KhoiTaoGiaoDienAccessory(ByVal flag As Boolean)
        btnEdit.Enabled = flag
        'btnDel.Enabled = flag
        btnUpdate.Enabled = Not flag
        btnCancel.Enabled = Not flag
        dtgAccessory.ReadOnly = flag
        dtgAccessory.Columns("AccessoryName").ReadOnly = True

        'Fix Progress
        If flag Then
            KhoiTaoGiaoDienRepair(flag)
        Else
            btnUpdateRepair.Enabled = False
            btnEditRepair.Enabled = False
            btnCancelRepair.Enabled = False
            dtgFixProgress.ReadOnly = True
        End If
    End Sub
#End Region

#Region "btn Edit, Del, Update, Cancel Repair"
    Private Sub btnEditRepair_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEditRepair.Click
        KhoiTaoGiaoDienRepair(False)
    End Sub

    Private Sub btnDeleteRepair_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelRepair.Click
        Dim ID_TruckAccessory As Integer = dtgAccessory.CurrentRow.Cells("ID_TruckAccessory").Value
        Dim order As Integer = dtgFixProgress.CurrentRow.Cells("RepairOrder").Value
        ''Update row new when change a primary key
        ''Delete and insert
        ''1.Delete
        Dim fixList = From p In db.tblFixProgresses
                   Where p.ID_TruckAccessory = ID_TruckAccessory And p.RepairOrder >= order
                   Select p

        For Each fixprogress In fixList
            Dim stt = fixprogress.RepairOrder

            If fixprogress.RepairOrder = order Then
                '1.Delete
                Dim fix = From p In db.tblFixProgresses
                           Where p.ID_TruckAccessory = ID_TruckAccessory And p.RepairOrder = stt
                           Select p
                db.tblFixProgresses.DeleteAllOnSubmit(fix)
                db.SubmitChanges()
            ElseIf fixprogress.RepairOrder > order Then

                '1.Delete
                Dim fix = (From p In db.tblFixProgresses
                           Where p.ID_TruckAccessory = ID_TruckAccessory And p.RepairOrder = stt
                           Select p).Single
                db.tblFixProgresses.DeleteOnSubmit(fix)
                db.SubmitChanges()

                '2. Insert
                Dim fixnew As New tblFixProgress
                fixnew.ID_TruckAccessory = ID_TruckAccessory
                fixnew.RepairOrder = stt - 1
                fixnew.DescriptionRepair = fix.DescriptionRepair
                fixnew.RepairDate = fix.RepairDate
                fixnew.RepairWarrantyDate = fix.RepairWarrantyDate
                fixnew.RepairPrice = fix.RepairPrice
                db.tblFixProgresses.InsertOnSubmit(fixnew)
                db.SubmitChanges()
            End If
        Next

        KhoiTaodtgFixProgress(ID_TruckAccessory)

        'Dim AccessoryName As String = ""
        'AccessoryName = dtgAccessory.CurrentRow.Cells("AccessoryName").Value

        'If MsgBox("Bạn muốn xóa phụ tùng " + AccessoryName + " và quá trình sửa chữa.", MsgBoxStyle.YesNo, "Chú ý") = MsgBoxResult.Yes Then
        '    Dim ID_TruckAccessory As Integer
        '    ID_TruckAccessory = dtgAccessory.CurrentRow.Cells("ID_TruckAccessory").Value

        '    'Del qua trinh sua chua
        '    Dim fix_progress = From p In db.tblFixProgresses
        '                       Where p.ID_TruckAccessory = ID_TruckAccessory
        '                       Select p

        '    db.tblFixProgresses.DeleteAllOnSubmit(fix_progress)
        '    db.SubmitChanges()

        '    'Del phu tung khoi xe
        '    Dim truck_accessory = From p In db.tblTruckAccessories
        '                       Where p.ID_TruckAccessory = ID_TruckAccessory
        '                       Select p
        '    db.tblTruckAccessories.DeleteAllOnSubmit(truck_accessory)
        '    db.SubmitChanges()

        '    Dim ID_Truck As Integer
        '    ID_Truck = cbbTruck.SelectedValue
        '    KhoiTaodtgAccessory(ID_Truck)
        'End If
    End Sub

    Private Sub btnUpdateRepair_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdateRepair.Click
        'dtgFixProgress is used
        'Cập nhật quá trình sửa chữa.
        'Cập nhật lại Order (đánh lại số thứ tự)
        Dim ID_TruckAccessory As Integer = dtgAccessory.CurrentRow.Cells("ID_TruckAccessory").Value

        Dim stt As Integer = 1
        For i As Integer = 0 To dtgFixProgress.Rows.Count - 2
            Dim order As Integer
            order = dtgFixProgress.Rows(i).Cells("RepairOrder").Value

            If dtgFixProgress.Rows(i).Cells("Status").Value = 1 Then
                ' Add row
                Dim fix As New tblFixProgress
                fix.ID_TruckAccessory = ID_TruckAccessory
                fix.RepairOrder = stt
                fix.DescriptionRepair = dtgFixProgress.Rows(i).Cells("DescriptionRepair").Value
                fix.RepairDate = dtgFixProgress.Rows(i).Cells("RepairDate").Value
                fix.RepairWarrantyDate = dtgFixProgress.Rows(i).Cells("RepairWarrantyDate").Value
                fix.RepairPrice = dtgFixProgress.Rows(i).Cells("RepairPrice").Value
                db.tblFixProgresses.InsertOnSubmit(fix)
                db.SubmitChanges()
            ElseIf dtgFixProgress.Rows(i).Cells("Status").Value = 2 Or dtgFixProgress.Rows(i).Cells("Status").Value = 0 Then
                ' Update row 

                'Dim fix = (From p In db.tblFixProgresses
                '           Where p.ID_TruckAccessory = ID_TruckAccessory And p.RepairOrder = order
                '           Select p).Single
                'fix.ID_TruckAccessory = ID_TruckAccessory
                'fix.RepairOrder = stt
                'fix.DescriptionRepair = dtgFixProgress.Rows(i).Cells("DescriptionRepair").Value
                'fix.RepairDate = dtgFixProgress.Rows(i).Cells("RepairDate").Value
                'fix.RepairWarrantyDate = dtgFixProgress.Rows(i).Cells("RepairWarrantyDate").Value
                'fix.RepairPrice = dtgFixProgress.Rows(i).Cells("RepairPrice").Value
                'db.SubmitChanges()

                'Update row new when change a primary key
                'Delete and insert
                '1.Delete
                Dim fix = From p In db.tblFixProgresses
                           Where p.ID_TruckAccessory = ID_TruckAccessory And p.RepairOrder = order
                           Select p
                db.tblFixProgresses.DeleteAllOnSubmit(fix)
                db.SubmitChanges()

                '2. Insert
                Dim fixnew As New tblFixProgress
                fixnew.ID_TruckAccessory = ID_TruckAccessory
                fixnew.RepairOrder = stt
                fixnew.DescriptionRepair = dtgFixProgress.Rows(i).Cells("DescriptionRepair").Value
                fixnew.RepairDate = dtgFixProgress.Rows(i).Cells("RepairDate").Value
                fixnew.RepairWarrantyDate = dtgFixProgress.Rows(i).Cells("RepairWarrantyDate").Value
                fixnew.RepairPrice = dtgFixProgress.Rows(i).Cells("RepairPrice").Value
                db.tblFixProgresses.InsertOnSubmit(fixnew)
                db.SubmitChanges()

            ElseIf dtgFixProgress.Rows(i).Cells("Status").Value = 3 Then
                ' Del row
                Dim fix = From p In db.tblFixProgresses
                           Where p.ID_TruckAccessory = ID_TruckAccessory And p.RepairOrder = order
                           Select p
                db.tblFixProgresses.DeleteAllOnSubmit(fix)
                db.SubmitChanges()
                stt -= 1
            End If
            stt += 1
        Next
        KhoiTaodtgFixProgress(ID_TruckAccessory)
        dtgAccessory.Enabled = True
        cbbTruck.Enabled = True
        dtgFixProgress.Enabled = True
        KhoiTaoGiaoDienRepair(True)
    End Sub

    Private Sub btnCancelRepair_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelRepair.Click
        KhoiTaoGiaoDienRepair(True)
    End Sub

    Public Sub KhoiTaoGiaoDienRepair(ByVal flag As Boolean)
        btnEditRepair.Enabled = flag
        btnDelRepair.Enabled = flag
        btnUpdateRepair.Enabled = Not flag
        btnCancelRepair.Enabled = Not flag
        dtgFixProgress.ReadOnly = flag
        dtgFixProgress.Columns("RepairOrder").ReadOnly = True

        'Accessory
        If flag Then
            cbbTruck.Enabled = True
            btnEdit.Enabled = True
            dtgAccessory.Enabled = True
            btnCopy.Enabled = True
        Else
            cbbTruck.Enabled = False
            btnUpdate.Enabled = False
            btnEdit.Enabled = False
            btnCancel.Enabled = False
            dtgAccessory.Enabled = False
            btnCopy.Enabled = False
        End If
    End Sub
#End Region
    
    Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
        KhoiTaolvAccessory()
    End Sub

    
End Class
